package order

import (
	"context"
	"gitee.com/tietang/terrace-go/v2/base/plugin"
	log "github.com/sirupsen/logrus"
	"reflect"
)

var _ CreateOrderDomainExt = new(CreateOrderDomainExtProxy1)

func GetCreateOrderDomainExtProxy1() *CreateOrderDomainExtProxy1 {
	ext := &CreateOrderDomainExtProxy1{}
	return ext
}

type CreateOrderDomainExtProxy1 struct {
	plugin.RuleChecker
	exts        []CreateOrderDomainExt
	isInit      bool
	ExtExecutor plugin.PluginExecutor
}

func (o *CreateOrderDomainExtProxy1) CanExe(in interface{}) bool {
	return true
}

func (o *CreateOrderDomainExtProxy1) getExts() []CreateOrderDomainExt {
	if o.isInit {
		return o.exts
	}
	defs, ok := plugin.Get(CreateOrderDomainPluginId)
	if !ok {
		return o.exts
	}
	o.exts = make([]CreateOrderDomainExt, len(defs))
	for i, def := range defs {
		o.exts[i] = def.Service.(CreateOrderDomainExt)
	}
	o.isInit = true
	return o.exts
}

func (o *CreateOrderDomainExtProxy1) PluginCode() string {
	return CreateOrderDomainPluginId
}

func (o *CreateOrderDomainExtProxy1) OnValidate(ctx context.Context, in *Order) error {
	for _, ext := range o.getExts() {
		if ce, ok := ext.(plugin.RuleChecker); ok {
			if !ce.Check(ctx, in) {
				continue
			}
		}

		log.Debug(o.PluginCode(), ":", reflect.TypeOf(ext).String())
		err := ext.OnValidate(ctx, in)
		if err != nil {
			return err
		}

	}
	return nil

}

func (o *CreateOrderDomainExtProxy1) PreSave(ctx context.Context, in *Order) error {
	for _, ext := range o.getExts() {
		if ce, ok := ext.(plugin.RuleChecker); ok {
			if !ce.Check(ctx, in) {
				continue
			}
		}
		log.Debug(o.PluginCode(), ":", reflect.TypeOf(ext).String())
		err := ext.PreSave(ctx, in)
		if err != nil {
			return err
		}
	}
	return nil

}
